import moment from 'moment'
import { reactive, toRefs } from 'vue'
import { useStore } from 'vuex'

export interface BaseQueryType {
  pageNum: number;
  pageSize: number;
}

export interface BaseDataType<T> {
  url: string;
  queryParams: BaseQueryType;
  dataList: Array<T>;
  total: number;
  selectList?: Array<T>;
}

export interface ResultType {
  total: number;
  data: Array<any>;
}
interface TableMType {
  dateFormat: (row: any, column: any) => void;
  timeFormat: (row: any, column: any) => void;
  handleSelectionChange: (val: any) => void;
  handleCurrentChange: (val: number) => void;
  getList: () => void;
  search: () => void;
}
export default function tableList(data?: BaseDataType<any>) {
  const store = useStore()
  const dateFormat = (row: any, column: any) => {
    const date = row[column.property]
    if (!date) {
      return null
    } else {
      return moment(date).format('YYYY-MM-DD')
    }
  }

  const timeFormat = (row: any, column: any) => {
    const date = row[column.property]
    if (!date) {
      return null
    } else {
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    }
  }

  const tableM = reactive<TableMType>({
    dateFormat: dateFormat,
    timeFormat: timeFormat,
    getList: () => {
      data && data.url && store.dispatch(data.url, data.queryParams).then((res: ResultType) => {
        data.dataList = res.data
        data.total = res.total
      }).catch()
    },
    handleSelectionChange: (val) => {
      data && (data.selectList = val)
    },
    handleCurrentChange: (val: number) => {
      data && (data.queryParams.pageNum = val)
      tableM.getList()
    },
    search: () => {
      data && (data.queryParams.pageNum = 1)
      tableM.getList()
    }
  })

  return {
    ...toRefs(tableM)
  }
}
